<template>
  <up-modal
    :show="showModal"
    title="温馨提示"
    :content="content"
    showCancelButton
    width="500rpx"
    confirmColor="#fab6bd"
    @confirm="operateOrder"
    @cancel="showModal = false"></up-modal>
  <view class="tabs">
    <up-tabs
      :list="statusList"
      @click="selectStatus"
      :activeStyle="{
        color: '#bb7755',
        fontWeight: 'bold',
        transform: 'scale(1.1)',
      }"
      lineColor="#bb7755"
      lineWidth="40"></up-tabs>
  </view>

  <view class="list" v-if="detailList.length > 0">
    <view class="item" v-for="item in detailList" :key="item.id">
      <view class="top">
        <view style="width: 100rpx; height: 20rpx; display: flex" class="tag">
          <up-tag
            text="自提"
            plain
            size="mini"
            type="warning"
            v-if="item.delivery === 'self'"></up-tag>
          <up-tag text="配送" plain size="mini" type="warning" v-else></up-tag>
        </view>
        <view class="create-time">{{ item.createTime }}</view>
        <view class="status">{{ item.status }}</view>
      </view>
      <view class="info" @click="goOrderDetail(item)">
        <view class="detail">
          <view class="dessert" v-for="el in item.detail" :key="el.id">
            <up-image
              :src="`http://localhost:8080/api/files/${el.dessert.dessertImg}`"
              width="120rpx"
              height="120rpx"></up-image>
            <text class="name">{{ el.dessert.dessertName }}</text>
          </view>
        </view>
        <view class="count">
          <view class="price">{{ '￥' + item.amount }}</view>
          <view class="num">共 {{ item.totalNum }} 件</view>
        </view>
      </view>
      <view
        class="operate"
        v-if="
          item.status === '待取货' ||
          item.status === '待收货' ||
          item.status === '待配送'
        ">
        <view class="cancel" @click="showConfim(item, false)">取消订单</view>
        <view class="btn">
          <up-button
            @click="showConfim(item, true)"
            type="warning"
            shape="circle"
            text="确认收货"
            :plain="true"></up-button>
        </view>
      </view>
      <view
        class="evaluate"
        v-if="item.published == false && item.status == '已完成'"
        @click="goComment(item)">
        去评价
      </view>
      <view
        class="evaluate"
        v-if="item.published == true"
        @click="seeComment(item)">
        查看评价
      </view>
    </view>
  </view>
  <up-empty mode="history" v-else></up-empty>
  <up-popup :show="showPopup" :round="10" closeIconPos="top-right">
    <view style="margin: 10rpx auto 20rpx">
      <up-rate
        count="5"
        v-model="comment.score"
        activeColor="#f9acb4"
        size="30"></up-rate>
    </view>
    <view style="margin-bottom: 20rpx">
      <up-textarea
        v-model="comment.content"
        placeholder="请输入评论内容"
        count></up-textarea>
    </view>
    <view
      style="
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 300rpx;
        margin: 0 auto 30rpx;
      ">
      <view
        @click="closePopup"
        style="
          width: 120rpx;
          height: 50rpx;
          border-radius: 100px;
          border: 1px solid #ccc;
          background-color: #e7e7e7;
          text-align: center;
          line-height: 50rpx;
        ">
        取消
      </view>
      <view
        style="
          width: 120rpx;
          height: 50rpx;
          border-radius: 100px;
          border: 1px solid #f9c2c4;
          background-color: #f9f1f1;
          text-align: center;
          line-height: 50rpx;
        "
        @click="publish">
        发布
      </view>
    </view>
  </up-popup>
  
  <up-popup :show="seeShow" :round="10" closeIconPos="top-right">
    <view style="margin: 10rpx auto 20rpx">
      <up-rate
        count="5"
        v-model="orderComment.score"
        activeColor="#f9acb4"
        size="30"
        readonly></up-rate>
    </view>
    <view style="margin-bottom: 20rpx">
      <up-textarea
        v-model="orderComment.content"
        count
        disabled></up-textarea>
    </view>
    <view
      style="
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 300rpx;
        margin: 0 auto 30rpx;
      ">
      <view
        @click="seeShow = false"
        style="
          width: 160rpx;
          height: 50rpx;
          margin: 0 auto;
          border-radius: 100px;
          border: 1px solid #ccc;
          background-color: #e7e7e7;
          text-align: center;
          line-height: 50rpx;
        ">
        取消
      </view>
    </view>
  </up-popup>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useUserStore } from '../../stores/user.js'
import {
  getOrderByUser,
  getOrderDetailService,
  confirmOrderService,
} from '../../api/order.js'
import { getDessertByIdService } from '../../api/dessert.js'
import { publishComment, updateBalance, getOrderComment } from '../../api/user.js'

const userStore = useUserStore()
const userId = userStore.userInfo.userId

const statusList = ref([
  { name: '全部' },
  { name: '待配送' },
  { name: '待收货' },
  { name: '待取货' },
  { name: '已完成' },
  { name: '已取消' },
])
// 点击切换
const detailList = ref([])
const selectStatus = (sel) => {
  if (sel.name === '全部') {
    detailList.value = orderList.value
  } else {
    detailList.value = orderList.value.filter(
      (item) => item.status === sel.name
    )
  }
}

// 发送请求获取订单列表
const orderList = ref([])
const details = ref([])
const desserts = ref([])
const totalNum = ref(0)
const publishs = ref({})
const getOrder = async () => {
  detailList.value = []
  const res1 = await getOrderByUser(userId, 'dessert')
  orderList.value = res1.data || []

  orderList.value.map(async (item) => {
    item.detail = []
    if (item.status == 1) {
      item.status = '待配送'
    } else if (item.status == 2) {
      item.status = '待收货'
    } else if (item.status == 3) {
      item.status = '待取货'
    } else if (item.status == 5) {
      item.status = '已完成'
    } else {
      item.status = '已取消'
    }
  })
  orderList.value.forEach(async (item) => {
    // 获取甜品详情
    const detail = await getOrderDetailService(item.id)
    details.value = detail.data || []
    
    // 获取甜品信息
    details.value.forEach(async (obj) => {
      desserts.value = []
      const dessert = await getDessertByIdService(obj.dessertId)
      obj.dessert = dessert.data
      item.detail.push(obj)
    })
    
    // 获取甜品的总数
    item.totalNum = details.value.reduce((acc, curr) => {
      return acc + curr.num
    }, 0)
    
    // 获取甜品是否已评论
    const comment = await getOrderComment(item.id)
    if(comment.code == 0) publishs.value = comment.data ?? {}
    item.published = Object.getOwnPropertyNames(publishs.value).length > 0 ? true : false
    detailList.value.push(item)
  })
}
onShow(() => {
  getOrder()
})

// 确认收货
const showModal = ref(false)
const content = ref('')
const confirm = ref({})
const flags = ref(false)
const showConfim = (item, flag) => {
  showModal.value = true
  confirm.value.id = item.id
  confirm.value.userId = item.userId
  confirm.value.username = item.username
  confirm.value.phone = item.phone
  confirm.value.address = item.address
  confirm.value.message = item.message
  confirm.value.time = item.time
  confirm.value.delivery = item.delivery
  confirm.value.amount = item.amount
  confirm.value.createTime = item.createTime
  confirm.value.type = item.type
  if (flag) {
    // 确认收货
    flags.value = flag
    content.value = '您确认已收货吗？'
    confirm.value.status = 5
  } else {
    // 取消订单
    flags.value = flag
    content.value = '您确认取消订单吗？'
    confirm.value.status = 6
  }
}

const operateOrder = async () => {
  // 发送请求 确认收货或确认取消订单
  const res = await confirmOrderService(confirm.value)
  if (res.code === '0') {
    // 取消订单
    if(confirm.value.status == 6) {
      const reduce = parseFloat(userStore.userInfo.balance + confirm.value.amount).toFixed(2)
      // 更新用户余额
      const balance = await updateBalance(userStore.userInfo.userId, reduce)
      if(balance.code == 0) {
        userStore.updateBalance(reduce)
      }
    }
    uni.showToast({
      title: flags.value ? '已确认收货' : '已取消订单',
      icon: 'none',
    })
    getOrder()
  } else {
    uni.showToast({
      title: flags.value
        ? '确认收货失败，请联系店家'
        : '取消订单失败，请联系店家',
      icon: 'none',
    })
  }
  showModal.value = false
}

// 跳转到订单详情页
const goOrderDetail = (item) => {
  uni.navigateTo({
    url: `/pages/orderDetail/orderDetail?order=${encodeURIComponent(
      JSON.stringify(item)
    )}`,
  })
}

// 去评价
const showPopup = ref(false)
const comment = ref({
  userId: userStore.userInfo.userId,
  username: userStore.userInfo.username,
  content: '',
  score: 0,
})

const commentOrder = ref({})
const goComment = (item) => {
  commentOrder.value = item
  showPopup.value = true
  comment.value.orderId = commentOrder.value.id
}

const closePopup = () => {
  showPopup.value = false
  comment.value.score = 0
  comment.value.content = ''
}

// 发布评论
const publish = async () => {
  const res = await publishComment(comment.value)
  if (res.code === '0') {
    uni.showToast({
      title: '发布成功！',
      icon: 'success',
    })
    // 标记订单状态为已评论
    commentOrder.value.status = 5
    await confirmOrderService(commentOrder.value)
    getOrder()
  } else {
    uni.showToast({
      title: res.message,
      icon: 'none',
    })
  }
  closePopup()
}

// 查看评价
const seeShow = ref(false)
const orderComment = ref({})
const seeComment = async (item) => {
    seeShow.value = true
    const res = await getOrderComment(item.id)
    
    if(res.code == 0) orderComment.value = res.data ?? {}
}
</script>

<style lang="scss" scoped>
.tabs {
  width: 102%;
  background-color: #fff;
  border-radius: 10rpx;
  text-align: center;
  box-sizing: border-box;
  margin-left: -10rpx;
  margin-bottom: 20rpx;
}

.list {
  width: 100%;
  text-align: center;
  .item {
    width: 95%;
    height: auto;
    background-color: #fff;
    border-radius: 10rpx;
    margin: 0 auto;
    padding: 10rpx 20rpx;
    box-sizing: border-box;
    margin-bottom: 10rpx;
    .top {
      display: flex;
      align-items: center;

      .create-time {
        font-size: 30rpx;
        color: #666;
        margin-left: 20rpx;
        margin-top: 10rpx;
      }

      .tag {
        margin-top: -10rpx;
      }

      .status {
        margin-left: auto;
      }
    }
    .info {
      width: 100%;
      display: flex;
      align-items: center;
      overflow: hidden;
      .detail {
        width: 500rpx;
        margin-top: 20rpx;
        display: flex;
        flex-wrap: nowrap;
        align-items: center;
        overflow-x: auto;

        .dessert {
          flex: 0 0 auto;
          width: 120rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: inline-block;
          text-align: center;
          margin-right: 10rpx;

          .name {
            font-size: 28rpx;
            color: #888;
          }
        }
      }

      .count {
        margin-top: 10rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;
        margin-left: auto;

        .price {
          font-weight: bold;
          font-size: 30rpx;
          color: #bb7755;
        }

        .num {
          font-size: 28rpx;
          color: #666;
        }
      }
    }

    .operate {
      width: 50%;
      display: flex;
      align-items: center;
      margin-left: auto;
      margin-right: -10rpx;

      .cancel {
        width: 50%;
        font-size: 28rpx;
        color: #666;
        transition: all linear 0.3s;
      }

      .btn {
        width: 50%;
      }
    }

    .evaluate {
      width: 180rpx;
      height: 70rpx;
      line-height: 70rpx;
      text-align: center;
      border-radius: 100px;
      background-color: rgba(250, 193, 106, 0.5);
      margin-left: auto;
      font-size: 28rpx;
      color: #222;
    }
  }
}
</style>
